package com.alili_tv.system.service.impl;

import com.alili_tv.system.entity.Tag;
import com.alili_tv.system.mapper.TagMapper;
import com.alili_tv.system.service.TagService;
import com.alili_tv.system.utils.AnsjUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.ansj.domain.Result;
import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.BaseAnalysis;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * <p>
 * 标签表 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2023-03-17
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {



    @Override
    public void mySaveOrUpdateBatch(List<Tag> list, Integer channelId) {
        if (list == null) return;
        for (Tag tag : list) {
            tag.setChannelId(channelId);
            LambdaUpdateWrapper<Tag> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper
                    .setSql("count = count + 1")
                    .eq(Tag::getName, tag.getName())
                    .eq(Tag::getChannelId, tag.getChannelId());
            // 保存时，如果数据已经存在，就增加count值，不存在就直接保存
            this.saveOrUpdate(tag, updateWrapper);
        }
    }

    @Override
    public List<Tag> getIdByChannelAndName(Integer channel, List<String> nameList) {
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .select(Tag::getId)
                .eq(Tag::getChannelId, channel)
                .in(Tag::getName, nameList);
        return this.list(queryWrapper);
    }

    /**
     * 获取到匹配关键词的tag id
     * @param text
     * @return
     */
    @Override
    public List<Long> searchTag(String text) {
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<Tag>()
                .select(Tag::getId);

        // 搜索内容长度大于3才使用分词器解析关键词
        if (text.length() > 3) {
            List<String> keywords = AnsjUtils.analyseKeyword(text);
            StringJoiner sj = new StringJoiner("|");
            for (String keyword : keywords) {
                sj.add(keyword);
            }
            queryWrapper.apply("name regexp '"+ sj + "'");
        } else {
            queryWrapper.like(Tag::getName, text);
        }
        List<Tag> tags = this.list(queryWrapper);

        return tags.stream().map(Tag::getId).distinct().toList();
    }



}
